package com.cbd.service.impl;

import com.cbd.common.UserStatus;
import com.cbd.dto.UserLoginDto;
import com.cbd.entity.UserEntity;
import com.cbd.mapper.UserMapper;
import com.cbd.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: CBD
 * @Date: 2024/11/22 10:36
 * @Description: 用户服务实现类
 */
@Service
@Slf4j
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    /**
     * 注册用户
     *
     * @param users 用户信息
     * @return 是否注册成功
     */
    @Transactional // 该注解用于事务控制
    @Override
    public boolean register(UserEntity users) {
        UserEntity existUser = userMapper.getUserByUsername(users.getUsername());
        if (existUser == null) {
            userMapper.insertUser(users);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 登录
     *
     * @param userDto 用户登录信息
     * @return 是否登录成功
     */
    @Override
    public boolean login(UserLoginDto userDto) {
        UserEntity existUser = userMapper.getUserByUsername(userDto.getUsername());
        return existUser.getPassword().equals(userDto.getPassword());
    }

    /**
     * 根据用户名获取用户信息
     *
     * @param username
     * @return
     */
    @Override
    public List<String> getRoles(String username) {
        List<String> roles = userMapper.getRoles(username);
        return roles;
    }

    @Override
    public List<String> getPermissions(String username) {
        List<String> permissions = userMapper.getPermissions(username);
        return permissions;
    }

    /**
     * 检查用户状态
     *
     * @param username 用户名
     * @return 用户状态
     */
    @Override
    @Transactional // 该注解用于事务控制
    public UserStatus checkUserStatus(String username) {
        UserEntity user = userMapper.getUserByUsername(username);
        return user != null ? UserStatus.values()[user.getStatus()] : UserStatus.PENDING;
    }

    /**
     * 更新用户状态
     *
     * @param username 用户名
     * @return 是否更新成功
     */
    @Override
    @Transactional // 该注解用于事务控制
    public boolean updateUserStatus(String username) {
        return userMapper.updateUserStatus(username);
    }
}


